package com.cn.qgx428.lazydiary.prump.service

import android.app.IntentService
import android.app.Service
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import android.util.Log
import com.cn.qgx428.lazydiary.extension.getCurrenTimePrecise
import com.cn.qgx428.lazydiary.prump.BaseClock
import com.cn.qgx428.lazydiary.prump.ClockManager
import com.cn.qgx428.lazydiary.prump.IClockAlarm
import java.util.*

class ClockService : IntentService("clock") {

    companion object {
        public  final val TAG: String = "ClockService"
    }

    lateinit var clockThread: Thread

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, " onCreate")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d("Clock", "onStartCommand")


        return super.onStartCommand(intent, flags, startId)
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "onDestroy")
    }

    override fun onHandleIntent(intent: Intent?) {
        clockThread = ClockThread()
        clockThread.run()
    }

    class ClockThread: Thread(){

        private var clock: IClockAlarm? = null

        override fun run() {
            while(true){
                // 当前定时提醒任务为空
                if (clock == null){

                    clock = ClockManager.getNextClock()
                    if (clock == null){
                        Log.d(TAG, "在等哦")
                        sleep(20000)
                        continue
                    }
                }
                else{
                    // 提醒时间到
                    if (clock!!.isAlarm()){
                        clock!!.alarm()
                        clock = null
                    } else{
                        // 睡眠
                        Log.d(TAG, "当前时间：" + Calendar.getInstance().getCurrenTimePrecise())
                        sleep(20000)
                    }
                }
            }
        }
    }
}

